﻿using System;
using System.Collections.Generic;

namespace LazyMapper.Core
{
    public class BinarySort<T> : ISorter<T>
    {
        private readonly Func<T, T, int> _compare;

        public BinarySort(Func<T, T, int> compare)
        {
            _compare = compare;
        }

        public void Sort(IList<T> toList)
        {
            bool changed;
            if (toList.Count <= 1) return;
            do
            {
                changed = false;
                for (int i = 0; i < toList.Count - 1; i++)
                {
                    if (_compare(toList[i], toList[i + 1]) > 0)
                    {
                        Swap(toList, i, i + 1);
                        changed = true;
                    }
                }
            } while (changed);
        }

        static void Swap(IList<T> list, int indexA, int indexB)
        {
            var tmp = list[indexA];
            list[indexA] = list[indexB];
            list[indexB] = tmp;
        }
    }
}